package com.example.networkinteraction.retrofit;

import com.example.networkinteraction.interceptor.HttpLoggingInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.util.concurrent.TimeUnit;

import static com.example.networkinteraction.constant.NetworkContant.TAG;
import static com.example.networkinteraction.constant.NetworkContant.TIME_OUT;

/**
 * Description:
 * File: RetrofitManager.java
 * Author: Administrator
 * Create: 2019/3/26 0026 下午 16:29
 */
public class RetrofitManager {
    private final Retrofit.Builder mBuilder;

    public RetrofitManager(Converter.Factory convertFactory, CallAdapter.Factory callAdapterFactory, String baseUrl) {
        mBuilder = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addCallAdapterFactory(callAdapterFactory)
                .addConverterFactory(convertFactory)
                .baseUrl(baseUrl);
    }

    public RetrofitManager(long timeout, Converter.Factory convertFactory, CallAdapter.Factory callAdapterFactory, String baseUrl) {
        mBuilder = new Retrofit.Builder()
                .client(getOkHttpClient(timeout))
                .addConverterFactory(convertFactory)
                .addCallAdapterFactory(callAdapterFactory)
                .baseUrl(baseUrl);
    }

    /**
     * 获取默认
     *
     * @return
     */
    private OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder()
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor(TAG))
                .build();
    }

    /**
     * 获取默认
     *
     * @return
     */
    private OkHttpClient getOkHttpClient(long timeout) {
        return new OkHttpClient.Builder()
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor(TAG))
                .build();
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>     class
     * @return <T>
     */
    public <T> T create(Class<T> service) {
        return mBuilder.build().create(service);
    }
}
